package utils;

import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.graphics.PDXObject;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.text.PDFTextStripperByArea;
import org.apache.pdfbox.util.Matrix;
import org.apache.pdfbox.contentstream.operator.DrawObject;
import org.apache.pdfbox.contentstream.operator.Operator;
import org.apache.pdfbox.contentstream.PDFStreamEngine;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.pdfbox.contentstream.operator.state.Concatenate;
import org.apache.pdfbox.contentstream.operator.state.Restore;
import org.apache.pdfbox.contentstream.operator.state.Save;
import org.apache.pdfbox.contentstream.operator.state.SetGraphicsStateParameters;
import org.apache.pdfbox.contentstream.operator.state.SetMatrix;

import javax.imageio.ImageIO;

public class GetImageLocationsAndSize extends PDFStreamEngine {
    int i = 0;
    public GetImageLocationsAndSize() {
        // preparing PDFStreamEngine
        addOperator(new Concatenate());
        addOperator(new DrawObject());
        addOperator(new SetGraphicsStateParameters());
        addOperator(new Save());
        addOperator(new Restore());
        addOperator(new SetMatrix());
    }

    public static void main(String[] args) throws IOException {
        String fileName = "D:\\Work\\ZZZ-report\\testAll\\2022-01-04\\1100001173536511.pdf";
        try (PDDocument document = PDDocument.load(new File(fileName))) {
            GetImageLocationsAndSize printer = new GetImageLocationsAndSize();
            int pageNum = 0;
            for (PDPage page : document.getPages()) {
                pageNum++;
//                System.out.println("Processing PDF page:" + pageNum + "\n-------------------------------- - ");
//                if (pageNum == 82) {
                printer.processPage(page);
//                }
            }
        }
    }

    protected void processOperator(Operator operator, List<COSBase> operands)
            throws IOException {
        String operation = operator.getName();
        String parentPath = "D:\\Work\\ZZZ-report\\testAll\\2022-01-04\\image4";
        if ("Do".equals(operation)) {
            COSName objectName = (COSName) operands.get(0);
            // get the PDF object
            PDXObject xobject = getResources().getXObject(objectName);
            // check if the object is an image object

            if (xobject instanceof PDImageXObject) {
                PDImageXObject image = (PDImageXObject) xobject;
                int imageWidth = image.getWidth();
                int imageHeight = image.getHeight();
                System.out.println("\nImage [" + objectName.getName() + "]");
                Matrix ctmNew = getGraphicsState().getCurrentTransformationMatrix();
                float imageXScale = ctmNew.getScalingFactorX();
                float imageYScale = ctmNew.getScalingFactorY();
                // position of image in the PDF in terms of user space units
                System.out.println("position in PDF = " + ctmNew.getTranslateX() + " " + ctmNew.getTranslateY() + " in user space units");
                // raw size in pixels
                System.out.println("raw image size  = " + imageWidth + " " + imageHeight + " in pixels");
                // displayed size in user space units
                System.out.println("displayed size  = " + imageXScale + " " + imageYScale + "in user space units");

                float pageWidth = getCurrentPage().getMediaBox().getWidth();
                float pageHeight = getCurrentPage().getMediaBox().getHeight();
                PDFTextStripperByArea stripper = new PDFTextStripperByArea();
                stripper.setSortByPosition(true);
                Rectangle rect = new Rectangle(0, (int) Math.rint(pageHeight - ctmNew.getTranslateY()), (int) Math.rint(pageWidth), 30);

//                PDFTextStripperByArea stripper = new PDFTextStripperByArea();
//                stripper.setSortByPosition(true);
//                Rectangle rect = new Rectangle(0, 600, 600, 30);
                stripper.addRegion("content", rect);
                stripper.extractRegions(getCurrentPage());
                String textContent = stripper.getTextForRegion("content");
                System.out.println(textContent);
                BufferedImage bufferedImage = image.getImage();
                String imageName;
                String content = textContent.replace("\r\n", "").replace(" ", "");
//                if (content.length() > 2) {
//                    imageName = content;
//                } else {
//                    imageName = "image" + (++i);
//                }
                i++;
                ImageIO.write(bufferedImage, "jpg", new File(parentPath + "\\" + i + ".jpg"));


            } else if (xobject instanceof PDFormXObject) {
                PDFormXObject form = (PDFormXObject) xobject;
                showForm(form);
            }
        } else {
            super.processOperator(operator, operands);
        }
    }
}